package top.lshaci.learning.wechat.offiaccount.controller;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import top.lshaci.learning.wechat.offiaccount.model.AbstractMessage;
import top.lshaci.learning.wechat.offiaccount.service.MessageService;
import top.lshaci.learning.wechat.offiaccount.util.WechatUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * WechatController
 *
 * @author lshaci
 * @since 1.0.0
 */
@Slf4j
@Controller
@AllArgsConstructor
public class WechatController {

    private final MessageService messageService;

    /**
     * <pre>
     *     若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。
     *     仅在提交配置URL和Token时调用
     * </pre>
     */
    @GetMapping("/signature")
    public void signature(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echoStr = request.getParameter("echostr");

        log.debug("signature: {}, timestamp: {}, nonce: {}, echoStr: {}", signature, timestamp, nonce, echoStr);
        if (!WechatUtil.checkSignature(signature, timestamp, nonce)) {
            log.debug("验签失败");
            response.getWriter().write("");
        } else {
            log.debug("验签成功");
            response.getWriter().write(echoStr);
        }
    }


    /**
     * <pre>
     *     接收微信用户发送的消息
     * </pre>
     */
    @PostMapping("/signature")
    public void receive(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");

        log.debug("signature: {}, timestamp: {}, nonce: {}", signature, timestamp, nonce);
        if (!WechatUtil.checkSignature(signature, timestamp, nonce)) {
            log.debug("验签失败");
            response.getWriter().write("");
            return;
        }
        AbstractMessage message = messageService.parse(request);
        System.err.println(message);

        String resp = "<xml>\n" +
                "  <ToUserName><![CDATA[" + message.getFromUserName() + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + message.getToUserName() + "]]></FromUserName>\n" +
                "  <CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[你好]]></Content>\n" +
                "</xml>";
        response.addHeader("Content-type", "application/xml;charset=utf8");
        response.getWriter().write(resp);
    }
}
